package com.leijie.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

/**
 * @author LeiJie
 * @time 2020-5-7 13:48
 * @desc TODO
 */
public class GrpcServer {

    private Server server;

    public static void main(String[] args) throws IOException, InterruptedException {
        final GrpcServer grpcServer = new GrpcServer();
        grpcServer.start();
    }


    public void start() throws IOException, InterruptedException {
        server = ServerBuilder.forPort(8899).addService(new PersionServiceImpl()).build().start();
        System.out.printf("Grpc 服务 [%d] 启动...\n",8899);
        blockUntilShutdown();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                GrpcServer.this.stop();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));
    }

    public void blockUntilShutdown() throws InterruptedException {
        if (server != null){
            server.awaitTermination();
        }
    }

    /**
     *
     * 功能描述:
     *
     * @返回: Stop等待30秒
     * @作者: LEI JIE
     * @时间: 2020-5-7 13:58
     */
    public void stop() throws InterruptedException {
        if (server != null){
            server.shutdown().awaitTermination();
        }
    }
}
